package com.kamikaze.docidset.impl;

import java.io.IOException;
import java.io.Serializable;

import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;

import com.kamikaze.docidset.api.DocSet;
import com.kamikaze.docidset.bitset.MyOpenBitSet;

public class OBSDocIdSet extends DocIdSet implements DocSet,Serializable 
{

  private static final long serialVersionUID = 1L;
  
  private MyOpenBitSet bitSet = null;
  int min = -1;
  int max = -1;
  
  
  public OBSDocIdSet(int length)
  {
    bitSet = new MyOpenBitSet(length); 
  }
  
  public void addDoc(int docid)
  {
    if(min == -1)
    {
      min = docid;
    }
    max = docid;
    bitSet.fastSetAs(max - min, 1);
   
  }
  
  class OBSDocIdSetIterator extends DocIdSetIterator
  {
    int lastReturn  = -1;
    

    @Override
    public int doc()
    {
       return lastReturn+min;
    }

    @Override
    public boolean next() throws IOException
    {
      
      if(bitSet.size()-1 > lastReturn)
      {
        if(lastReturn  == -1)
        {  
          
          if(bitSet.fastGet(0)){
            lastReturn = 0;
            return true;
          }
        }
        else
          lastReturn = bitSet.nextSetBit(lastReturn+1);
        
        if(lastReturn!=-1)
          return true;
      }
      return false;
   
    }

    @Override
    public boolean skipTo(int target) throws IOException
    {
      if(target - min > size())
        return false;
      else
      {
        lastReturn = bitSet.nextSetBit(target - min);
        if(lastReturn != -1)
          return true;
      }
      return false;
        
    }

    @Override
    public int getCursor()
    {
      return 0;
    }
  }
 
  @Override
  public DocIdSetIterator iterator()
  {
    return new OBSDocIdSetIterator();
  }

  
  public int size()
  {
    return (int) this.bitSet.size();
  }

  public int find(int val)
  {
        val-=min;
        if(bitSet.get(val))
        {
          return 1;
        }
        else
          return -1;
       
  }


  
}
